from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from common import getHotData
from utils.RedisUtils import redis_pool

# fastapi生命周期事件
@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时的初始化
    print("应用启动")
    yield
    # 退出时的清理操作
    print("应用关闭")
    # 关闭redis连接池
    await redis_pool.disconnect()

# 配置fastapi实例
app = FastAPI(lifespan=lifespan)

# 配置跨域
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 热点数据初始配置
map = {
    "toutiao": "今日头条",
    "baidu": "百度热搜"
}

# 获取所有热点信息
@app.get("/rank/todayTopNews")
async def getTodayTopNews():
    result = []
    for key in map.keys():
        try:
            name = map.get(key)
            data = await getHotData(name, key)
            result.append(data)
        except Exception as e:
            print(f"处理 key: {key} 时出错: {e}")
            continue  # 继续处理下一个 key
    return {
        "code": 200,
        "msg": "success",
        "data": result
    }

# 获取指定热点信息
@app.get("/rank/{item_id}")
async def get_data(item_id: str):
    if item_id not in map:
        return {"error": "参数异常"}
    name = map.get(item_id)
    data = await getHotData(name, item_id)
    return {
        "code": 200,
        "msg": "success",
        "data": data
    }

# 启动入口
if __name__  == '__main__':
    import uvicorn
    uvicorn.run(app, host='127.0.0.1', port=8000)